package menu

import (
	"context"
	"github.com/pkg/errors"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuCreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuCreateLogic {
	return &MenuCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuCreateLogic) MenuCreate(req *types.MenuCreateRo) (resp *types.BaseRsp, err error) {
	if req.ParentId > 0 {
		var parent model.MenuConfig
		if err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.ParentId).
			First(&parent).Error; err != nil {
			return nil, errors.Wrap(err, "父菜单不存在")
		}
		if parent.Typ != 1 {
			return nil, errors.Wrap(err, "父菜单不是分组，不能添加子菜单")
		}
	}

	err = l.svcCtx.DB.WithContext(l.ctx).Create(&model.MenuConfig{
		Name:     req.Name,
		Typ:      req.Typ,
		Memo:     req.Memo,
		ParentId: req.ParentId,
		Sequence: req.Sequence,
		Path:     req.Path,
	}).Error
	return
}
